
import sys
from Class.Serial_Com import Serial_com
import threading
from time import sleep
from Class.CSConfig import CSConfig
from Class.StandardMode import *
import copy
from Class.UserInfo import UserInfo
from Class.Format import Serialization
from Class.SystemConfig import SystemConfig, Settings
from Class.Format import Format
from Class.DeviceBase import *

class CS598(DeviceBase):
    def __init__(self):
        super().__init__()
        self.monitor = Monitor()
        self.card = Serial_com()
        self.card.sigReceive.connect(self.monitorRefresh)
        self.card.sigReceive.connect(self.baselineControl)
        self.sigBaseLineUpdate.connect(self.dataupdate)
        self.config = CSConfig()
        self.systemconfig = SystemConfig()
        self.settings = Settings()
        inPutPath = os.path.abspath(sys.argv[0])
        self.configFolder = os.path.join(os.path.dirname(inPutPath), "cs")
        self.configDefaultName = "default.bin"
        self.analyseStop = True
        self.obtainResults = False
        self.enableAcq = False  # 开始采集释放曲线
        self.modelResult = ResultMode()
        self.modelReport=ResultMode()
        self.baseData = BaseData()  # 基线状态
        self.vs = VoltSignal()
        self.acqEvent = None
        self.threadPower = None  # 高频后台线程
        self.bHFPower = False  # true高频灯丝打开，false高频灯丝关闭
        self.bPreHeating = False  # true高频正在预热
        self.bIgnorCounts = False  # True 忽略预热计时
        self.regulatePIDStop = True  # 标识regulatePID终止
        self.bRefreshVimax = True  # True 更新Vimax,当调试页面查看调零后基线时或进入等待状态后，不再更新
        self.bFurnaceUp = False #True:正在升炉冲洗

    def monitorRefresh(self, pts):
        """更新仪器状态点"""
        self.monitor.DILiftFurnace = (pts.DIValue & (1 << cs_598.systemconfig.daq.DILiftFurnace)) != 0
        self.monitor.DIBrush = (pts.DIValue & (1 << cs_598.systemconfig.daq.DIBrush)) != 0
        self.monitor.ADPressure = pts.ChannelV[cs_598.systemconfig.daq.ADPressure] * 0.0263-0.0402
        self.monitor.ADFlow = pts.ChannelV[cs_598.systemconfig.daq.ADMFC]
        self.monitor.ReformerT = pts.ChannelV[cs_598.systemconfig.daq.ADReformerT]
        self.monitor.errorcarrier = self.monitor.ADFlow < 1
        self.monitor.errorcarrierpressure = self.monitor.ADPressure < 0.05
        self.sigStatusUpdate.emit(self.monitor)

    # region 配置
    def deinit(self):
        """将方法二进制序列化到文件"""
        self.saveSettings()
        self.saveconfig()

    def saveconfig(self):
        """序列化方法到文件，并记录当前方法名"""
        filepath = os.path.join(self.configFolder, self.config.name + ".bin")
        Serialization.serializeToFile(filepath, self.config)
        defaultpath = os.path.join(self.configFolder, "default.txt")
        with open(defaultpath, "w") as f:
            f.write(self.config.name)

    def saveSettings(self):
        """序列化系统配置到文件"""
        print("saveSettings")
        print(self.settings.resultcolHidden)
        filepath = os.path.join(self.configFolder, "Settings.bin")
        Serialization.serializeToFile(filepath, self.settings)

    def init(self, path):
        dbPath = os.path.join(path, "cs")
        if dataBase.initDB(dbPath):
            self.getSettings()
            filepath = os.path.join(self.configFolder, "default.txt")
            config = None
            if os.path.exists(filepath):
                with open(filepath, 'r') as file:
                    method = file.readline()
                    if len(method) != 0:
                        config = self.getconfig(method)
            if config is not None:
                self.config = config
                Format.decimals = self.config.decimals
            else:  # 第一次登录，先保存下配置文件
                self.deinit()
            return True
        else:
            return False

    def getSettings(self):
        """反序列化得到系统配置"""
        print("getSettings")
        config = None
        filepath = os.path.join(self.configFolder, "Settings.bin")
        config = Serialization.deserialize(filepath)
        if config is not None:
            self.settings = config
        print(self.settings,dir(self.settings))
        print(self.settings.resultcolHidden)
    def getconfig(self, name):
        """
        反序列化方法文件
        :param name:
        :return: 方法对象，序列化失败或者文件不存在，返回None
        """
        config = CSConfig()
        filepath = os.path.join(self.configFolder, name + ".bin")
        configtemp = Serialization.deserialize(filepath)
        if configtemp is not None:
            #region 新增、删除属性
            for name, value in vars(configtemp).items():
                if hasattr(config, name):
                    if name == "factors":
                        for index,factor in enumerate(value):
                            for propertyname, propertyvalue in vars(factor).items():
                                if hasattr(config.factors[index], propertyname):
                                    setattr(config.factors[index], propertyname, propertyvalue)
                    elif name=="baseItems":
                        for index,channelData in enumerate(value):#每个通道
                            if len(channelData) >0:
                                for baseItem in channelData:
                                    item = BaseCalibrationItem()
                                    for propertyname, propertyvalue in vars(baseItem).items():
                                        if hasattr(item, propertyname):
                                            setattr(item, propertyname, propertyvalue)
                                    config.baseItems[index].append(item)
                    else:
                        setattr(config, name, value)
            # region 新增、删除属性
            # for name, value in vars(configtemp).items():
            #     if not hasattr(config, name):
            #         setattr(config, name, value)
            # delattrlist = []
            # for name, value in vars(config).items():
            #     if not hasattr(configtemp, name):
            #         delattrlist.append(name)
            # for i in delattrlist:
            #     delattr(config, i)
            # if not hasattr(config.factors[0], "blankarea"):
            #     for i in range(dataBase.maxChannel):
            #         setattr(config.factors[i], "blankarea", 0)
            # endregion
        return config
    # endregion

    # region 基线
    def baselineControl(self, pts):
        '''基线处理：判断稳定、求均值、调零,释放基线更新信号'''
        baseline_init = []
        for i in range(dataBase.maxChannel):
            baseline_init.append(pts.ChannelV[self.systemconfig.daq.ADBaseline[i]])
            # 滤波处理
            # if self.baseline_last[i] == -99:
            #         self.baseline_last[i] = baseline_list[i]
            # if self.systemconfig.daq.filterC != 1:
            #     baseline_list[i] = self.systemconfig.daq.filterC * baseline_list[i] + \
            #                        (1-self.systemconfig.daq.filterC) * self.baseline_last[i]
            # self.baseline_last[i] = baseline_list[i]
        baseline_zero = [0 for i in range(dataBase.maxChannel)]  # 处理后
        for i in range(dataBase.maxChannel):
            if self.config.channels[i].enable:
                # 若启用通道，则调零、求均值
                # <editor-fold desc="非释放曲线状态下，记录定长基线，计算均值">
                if not self.enableAcq and self.bRefreshVimax:
                    self.baseData.channels[i].data.append(baseline_init[i])
                    while len(self.baseData.channels[i].data) > self.systemconfig.daq.freq * self.config.baselineTime:
                        self.baseData.channels[i].data[:-1] = self.baseData.channels[i].data[1:]
                        self.baseData.channels[i].data.pop()
                    self.baseData.channels[i].stable += 1
                    self.baseData.channels[i].average = Factor.calculateAverage(self.baseData.channels[i].data)
                else:
                    self.baseData.channels[i].data.clear()
                # </editor-fold>
                # <editor-fold desc="处理基线数据">
                baseline_zero[i] = Factor.convertToZeroV(self.baseData.channels[i].average, baseline_init[i],
                                                           True if i > 1 else False)
                # </editor-fold>
                if baseline_zero[i] * 1000 > self.config.baselineDeviation:
                    self.baseData.channels[i].stable = 0
        data = [pts.UpContainer, baseline_init, baseline_zero]
        self.sigBaseLineUpdate.emit(data)
        self.baselineCheckStability()

    def baselineCheckStability(self):
        '''判断基线是否稳定：在指定时间内，都处于偏差范围内'''
        count = self.config.baselineTime * self.systemconfig.daq.freq
        stable = True
        for i in range(dataBase.maxChannel):
            if self.config.channels[i].enable and self.baseData.channels[i].stable < count:
                stable = False
        self.baseData.isStable = stable
    # endregion
    def tipAndSleep(self, s, time=0):
        """
        触发sigStatusTip信号，延迟time*1000s
        :param s:传递的信息
        :param time:延迟时间，单位s,默认不延迟
        """
        self.sigStatusTip.emit(s)
        # print(s)
        if time > 0:
            s = time / 10.0
            for i in range(10):
                sleep(s)
                self.sigWaitting.emit(i + 1)

    # region 分析时序
    def analyseStart(self, sampleInfo):
        self.analyseStop = False
        self.obtainResults = True
        self.acqEvent = None
        self.vs = VoltSignal()
        self.vs.result.SampleName = sampleInfo.sampleName
        self.vs.result.SampleNum = sampleInfo.sampleNum
        self.vs.sampleId = datetime.datetime.now()
        self.vs.result.FluxWeight = sampleInfo.fluxWeight
        self.vs.result.SampleWeight = sampleInfo.sampleWeight
        self.vs.result.MethodName = self.config.name
        # self.vs.result.UserName = UserInfo.currentUser
        # 设置通道全部打开
        self.vs.result.Channel = 0x05
        self.vs.factors.clear()
        self.vs.channels.clear()

        for i in range(dataBase.maxChannel):
            self.vs.factors.append(copy.copy(self.config.factors[i]))
            self.vs.channels.append(self.config.channels[i].enable)

        t = threading.Thread(target=self.demoTest)
        # 后台线程
        t.setDaemon(True)
        t.start()

    def analyse_stop(self):
        """停止分析"""
        if self.acqEvent is not None:
            self.acqEvent.set()
        self.analyseStop = True
        self.closePID()

    def demoTest(self):
        if not self.analyseStop:
            self.taskNewSeq()
        self.obtainResult()
        self.reset()
        self.tipAndSleep("分析完成")

    def obtainResult(self):
        if self.obtainResults:
            self.vs.calculateResult()
            if self.vs.addAll():
                print("添加数据库成功")
                self.addResult(self.modelResult, self.vs.result)
                self.sigUpdateNewResult.emit(self.vs.result)
            else:
                print("添加数据库失败")

    def taskNewSeq(self):
        # <editor-fold desc="仪器控制">
        if not self.openGas():
            return
        self.tipAndSleep("升炉")
        self.bFurnaceUp = True
        self.cardOpenValve(self.systemconfig.daq.valveExhauster,  # 吸尘
                           self.systemconfig.daq.valveEvacuate,  # 排空
                           self.systemconfig.daq.valveBackblow,  # 反吹
                           self.systemconfig.daq.valveFurnaceChamber,  # 炉室
                           self.systemconfig.daq.valveLance,  # 氧枪
                           self.systemconfig.daq.valveUpDown)  # 升炉
        self.cardCloseValve((self.systemconfig.daq.valveFurnaceRear))  # 炉后
        self.cardOutput()
        sleep(2)
        self.cardCloseValve(self.systemconfig.daq.valveLance,
                            self.systemconfig.daq.valveExhauster)
        self.cardOutput()
        self.tipAndSleep("检查升炉状态")
        if not self.checkFurnaceLift():
            self.tipAndSleep("升炉失败")
            return
        self.tipAndSleep("冲洗")
        sleep(self.config.timePurge)
        self.cardCloseValve(self.systemconfig.daq.valveBackblow,  # 关反吹
                            self.systemconfig.daq.valveEvacuate)  # 关排空
        self.cardOpenValve(self.systemconfig.daq.valveFurnaceRear)  # 开炉后
        self.cardOutput()
        self.bFurnaceUp = False
        if self.analyseStop:
            return
        self.tipAndSleep("等待" + str(self.config.waitingT) + "s", self.config.waitingT)
        while not (self.baseData.forceAnalyse or self.baseData.isStable):
            self.tipAndSleep("等待基线稳定")
            if self.analyseStop:
                return
            sleep(0.5)
        self.obtainResults = True
        self.tipAndSleep("开启高频")
        self.threadPower = threading.Thread(target=self.regulatePID)
        self.threadPower.setDaemon(True)
        self.threadPower.start()
        t2 = self.config.timeLance  # 开氧枪延迟时间
        th2 = threading.Thread(target=self.taskOpenLance, kwargs={"t": t2})
        th2.setDaemon(True)
        th2.start()
        t3 = t2 + self.config.timeChamber  # 氧枪关闭后，再延迟一定时间关炉室
        th3 = threading.Thread(target=self.taskCloseChamber, kwargs={"t": t3})
        th3.setDaemon(True)
        th3.start()
        # </editor-fold>
        self.tipAndSleep("开始采集")
        self.acq()

    def acq(self):
        """采集"""
        self.acqCount = 0
        self.integralDelayCount = 0
        self.lastTick = 0
        self.lastTime = 0.0
        self.stop = [False for x in range(dataBase.maxChannel)]
        self.sumDelay = [0.0 for x in range(dataBase.maxChannel)]
        self.max = [0.0 for x in range(dataBase.maxChannel)]
        self.peakMax = 10000

        for i in range(0, dataBase.maxChannel):
            # 记录基准电压
            self.vs.setaverageV(i, self.baseData.channels[i].average)
            # TODO获取基线均值，设置最大值max
            if bool(1 - self.config.channels[i].enable):  # 关闭方法中未打开的通道
                self.stop[i] = True
                t = 1 << i
                t = ~t
                self.vs.result.Channel = self.vs.result.Channel & t
            elif (i % 2 == 1) and self.config.channels[i - 1].enable:  # 高低同时打开时，关闭高通道
                t = 1 << i
                t = ~t
                self.vs.result.Channel = self.vs.result.Channel & t
        self.sigCurveLineAddPoint.emit(-1, 0, 0)  # -1 清理释放曲线
        if not self.analyseStop:
            self.acqEvent = threading.Event()  # 用于停止线程的标识
            self.enableAcq = True  # 触发DataReceive 开始接收数据
            self.acqEvent.wait()  # 暂停线程运行，等待set信号
        self.enableAcq = False
        self.analyseStop = True

    def dataupdate(self, data):
        if bool(1 - self.enableAcq):
            return
        if self.analyseStop:
            self.acqEvent.set()  # 将running设置为True，继续线程运行
        upcontainer = data[0]
        t = 0.0
        if self.acqCount > 0:
            if upcontainer > self.lastTick:
                t = self.lastTime + (upcontainer - self.lastTick) / float(self.systemconfig.daq.freq)
            else:
                if upcontainer < self.lastTick:
                    t = self.lastTime + (upcontainer + 256 - self.lastTick) / float(self.systemconfig.daq.freq)
        self.lastTime = t
        self.lastTick = upcontainer
        self.vs.addT(t)

        self.acqCount += 1
        v = [0.0 for x in range(0, dataBase.maxChannel)]
        for i in range(dataBase.maxChannel):
            v[i] = data[2][i]
            if t == 0:  # 给各通道均值赋初值
                self.vs.average[i] = v[i]
                # 积分延迟时间，记录均值
            if t < self.config.channels[i].delay:
                if self.config.channels[i].delay > 2:#取后2s的均值
                    if t > self.config.channels[i].delay - 2:
                        self.sumDelay[i] += v[i]
                        self.integralDelayCount +=1
                        self.vs.average[i] = self.sumDelay[i] / self.integralDelayCount
                else:
                    self.sumDelay[i] += v[i]
                    self.vs.average[i] = self.sumDelay[i] / self.acqCount
                # 把原始积分延迟曲线记录下来
                self.vs.addValueDelay(i, v[i])
                v[i] = 0
            else:
                v[i] = v[i] - self.vs.average[i]
            if self.analyseStop:
                self.stop[i] = True
            #     记录最大峰值，判断积分结束，加载数据到vs
            if bool(1 - self.stop[i]):
                # 绘制释放曲线
                self.sigCurveLineAddPoint.emit(i, t, v[i])
                self.vs.addValue(i, v[i])
                if v[i] > self.max[i]:
                    self.max[i] = v[i]
                if False and v[i] > self.peakMax:
                    self.stop[i] = True
                    print("超出了最大峰值")
                else:
                    if (t > self.config.channels[i].min and
                            v[i] < self.max[i] * self.config.channels[i].ratio + self.config.channels[
                                i].comporator * 0.001
                            or t > self.config.channels[i].max):
                        self.stop[i] = True

        if False not in self.stop:
            # <editor-fold desc="设置结果通道">
            if self.config.channels[0].enable and self.config.channels[1].enable:
                if self.max[0] > self.config.switch1:  # 高低同时开启，超过切换电压，切换到高通道
                    self.vs.result.Channel = self.vs.result.Channel & 0xFE
                    self.vs.result.Channel = self.vs.result.Channel | 0x02
            elif self.config.channels[0].enable:
                if self.max[0] > self.peakMax:  # 只开启了低通道，超过峰值，复位两个通道，异常！
                    self.vs.result.Channel = self.vs.result.Channel & 0xFC
            if self.config.channels[2].enable and self.config.channels[3].enable:
                if self.max[2] > self.config.switch1:  # 高低同时开启，超过切换电压，切换到高通道
                    self.vs.result.Channel = self.vs.result.Channel & 0xFB
                    self.vs.result.Channel = self.vs.result.Channel | 0x08
            elif self.config.channels[2].enable:
                if self.max[2] > self.peakMax:  # 只开启了低通道，超过峰值，复位两个通道，异常！
                    self.vs.result.Channel = self.vs.result.Channel & 0xF3
            # </editor-fold>
            self.acqEvent.set()  # 将running设置为True，继续线程运行
    # endregion

    # <editor-fold desc="仪器操作">
    def hfPowerOperation(self):
        """根据高频灯丝当前状态，取反操作，返回当前状态"""
        self.bHFPower = self.cardGetDO(self.systemconfig.daq.valveHFPower)
        if self.bHFPower:
            self.finishHFPower()
        else:
            self.cardOpenValve(self.systemconfig.daq.valveHFPower)
            self.cardOutput()
            self.bHFPower = True
            # 开启线程预热计时
            t = threading.Thread(target=self.preHeatHFPower)
            # 后台线程
            t.setDaemon(True)
            t.start()
        return self.bHFPower

    def preHeatHFPower(self):
        """等待高频灯丝预热300s"""
        self.bPreHeating = True
        self.bIgnorCounts = False
        count = 300
        while (not self.bIgnorCounts) and self.bHFPower:
            self.tipAndSleep("等待预热" + str(count) + "s")
            sleep(1)
            count -= 1
            if count == 0:
                break
        self.bPreHeating = False
        self.bIgnorCounts = False
        self.tipAndSleep("高频就绪")

    def finishHFPower(self):
        """关闭高频灯丝，如果再执行等待预热，则结束预热"""
        self.cardCloseValve(self.systemconfig.daq.valveHFPower)
        self.cardOutput()
        self.bHFPower = False
        self.bPreHeating = False

    def reset(self):
        """复位时，停止高频预热，降炉，设置流量"""
        self.bIgnorCounts = True
        self.furnaceOperation(down=True)
        self.tipAndSleep("就绪")

    def reset1(self):
        """复位时，停止高频预热，设置流量,灯丝电源和炉子状态保持不变"""
        self.bIgnorCounts = True
        self.closePID()
        sleep(0.5)
        self.cardAO(self.systemconfig.daq.DAPower, 0)
        sleep(0.5)
        self.initGas()
        self.cardCloseValve(self.systemconfig.daq.valveEvacuate,
                            self.systemconfig.daq.valveFurnaceRear,
                            self.systemconfig.daq.valveLance,
                            self.systemconfig.daq.valveFurnaceChamber,
                            self.systemconfig.daq.valveBrushFurnace,
                            self.systemconfig.daq.valveExhauster)
        self.cardOutput()
        self.tipAndSleep('就绪')
        self.sigSetStartEnable.emit(True)
        self.tipAndSleep("就绪")

    def taskOpenLance(self, t):
        '''延迟t秒后再开启氧枪'''
        count = 10
        delay = float(t) / 10
        while (not self.analyseStop) and (count > 0):
            sleep(delay)
            count -= 1
        if not self.analyseStop:
            self.cardOpenValve(self.systemconfig.daq.valveLance)
            self.cardOutput()

    def taskCloseChamber(self, t):
        """延迟关闭炉室"""
        count = 10
        delay = float(t) / 10
        while (not self.analyseStop) and (count > 0):
            sleep(delay)
            count -= 1
        if not self.analyseStop:
            self.cardCloseValve(self.systemconfig.daq.valveFurnaceChamber)
            self.cardOutput()

    def regulatePID(self):
        '''高频控制'''
        count = 0
        delay = 0.0
        while (not self.analyseStop) and (delay < self.config.powerDelay):
            self.regulatePIDStop = False
            count += 1
            outvolt = count * 2
            if outvolt > self.config.powerUplimit:
                outvolt = self.config.powerUplimit
            self.cardAO(self.systemconfig.daq.DAPower, outvolt)
            sleep(0.2)
            delay = count * 0.3  # 因为每次发送AO延迟了0.1S，所以这里是0.3
        self.regulatePIDStop = True
        self.closePID()

    def closePID(self):
        '''关闭高频'''
        self.cardAO(self.systemconfig.daq.DAPower, 0)
        while not self.regulatePIDStop:
            sleep(0.01)
        self.cardAO(self.systemconfig.daq.DAPower, 0)

    def close_card(self):
        if self.card.isOpen():
            self.analyseStop = True
            self.closePID()
            self.flowregulate(False)
            self.card.close()

    def link_card(self):
        self.card.setPortName(self.settings.DAQCom)
        self.card.link_card()
        if self.card.isLinked:
            self.initGas()

    def cardGetDO(self, index):
        """返回指定DO的当前输出值"""
        return self.card.getChannelDO(index)

    def cardOpenValve(self, *index):
        for i in index:
            self.card.setChannelDO(i, True)

    def cardCloseValve(self, *index):
        for i in index:
            self.card.setChannelDO(i, False)

    def cardAO(self, index, value):
        if index == self.systemconfig.daq.DAPower and value > 0:
            if not self.monitor.DILiftFurnace:
                return
        self.card.writeChannelAO(index, value)

    def cardOutput(self):
        return self.card.outputDO()

    def initGas(self):
        """开机初始化仪器状态"""
        self.cardOpenValve(self.systemconfig.daq.valveGeneralOxyen,
                           self.systemconfig.daq.valveBackblow,
                           self.systemconfig.daq.valveEmit)
        self.cardOutput()
        sleep(0.1)
        self.flowregulate(True, self.config.autoSaving)

    def flowregulate(self, isopen=True, isSavingGas = False):
        '''流量控制'''
        isopen = False if isSavingGas else isopen
        self.cardAO(self.systemconfig.daq.DAMFC, 2.2 if isopen else 0)

    def checkFurnaceLift(self):
        '''检查升炉状态，升炉，返回True'''
        if True or self.config.useSensors:
            count = 10
            while count > 0:
                if self.monitor.DILiftFurnace:
                    return True
                sleep(1)
                count -= 1
            return False
        else:
            sleep(2)
            return True

    def openGas(self):
        return self.openCarriergas() and self.checkPneumatic()

    def openCarriergas(self):
        self.cardOpenValve(self.systemconfig.daq.valveGeneralOxyen)
        self.cardOutput()
        return True

    def checkPneumatic(self):
        return True

    def furnaceOperation(self, down=False):
        if self.checkPneumatic():
            if self.monitor.DILiftFurnace or down:
                t = threading.Thread(target=self.downFurnace)
                # 后台线程
                t.setDaemon(True)
                t.start()
            else:
                if self.monitor.DIBrush:
                    # 升炉
                    self.cardOpenValve(self.systemconfig.daq.valveUpDown)
                    self.cardOutput()
                else:
                    QMessageBox.warning(None, "提示", "炉刷未复位，无法升炉")
                self.sigSetStartEnable.emit(True)
        else:
            self.sigSetStartEnable.emit(True)

    def exhausterOperation(self):
        if self.checkPneumatic():
            bOPen = self.cardGetDO(self.systemconfig.daq.valveExhauster)
            if bOPen:
                self.cardCloseValve(self.systemconfig.daq.valveExhauster)
                self.cardOutput()
            else:
                self.cardOpenValve(self.systemconfig.daq.valveExhauster)
                self.cardOutput()

    def downFurnace(self):
        '''降炉操作'''
        self.closePID()
        sleep(0.5)
        self.cardAO(self.systemconfig.daq.DAPower, 0)
        sleep(0.5)
        self.initGas()
        self.cardOpenValve(self.systemconfig.daq.valveEvacuate)
        self.cardCloseValve(self.systemconfig.daq.valveFurnaceRear,
                            self.systemconfig.daq.valveLance,
                            self.systemconfig.daq.valveFurnaceChamber)
        self.cardOutput()
        self.tipAndSleep('等待冲洗' + str(self.config.timePurge) + 's', self.config.timePurge)
        self.cardCloseValve(self.systemconfig.daq.valveUpDown)
        self.cardOpenValve(self.systemconfig.daq.valveExhauster)
        self.cardOutput()
        self.tipAndSleep('等待2s', 2)
        self.cardOpenValve(self.systemconfig.daq.valveBrushFurnace)
        self.cardOutput()
        self.tipAndSleep('等待2s', 2)
        self.cardCloseValve(self.systemconfig.daq.valveBrushFurnace)
        self.cardOutput()
        self.tipAndSleep('等待2s', 2)
        self.cardCloseValve(self.systemconfig.daq.valveExhauster,
                            self.systemconfig.daq.valveEvacuate)
        self.cardOutput()
        self.tipAndSleep('就绪')
        self.sigSetStartEnable.emit(True)
    # </editor-fold>
    def getresultcolHidden(self):
        return self.settings.resultcolHidden
    def getDAQCom(self):
        return self.settings.DAQCom

    def setDAQCom(self, com):
        self.settings.DAQCom = com

    def setupRow(self,model, row, r):
        '''
        将DBResult结果更新到model中的指定行
        :param row: 行号
        :param r: 结果
        :return:
        '''
        for j in range(0, dataBase.colNum):
            value = None
            if j == dataBase.dbColId[1]:
                value = r.SampleId.strftime("%Y-%m-%d %H:%M:%S")
            elif j == 1:
                value = r.SampleName
            elif j == 2:
                value = r.SampleNum
            elif j == 3:
                value = r.SampleWeight
            elif j == 4:
                value = r.FluxWeight
            elif j == 5:
                value = r.Content01
            elif j == 6:
                value = r.Content02
            elif j == 7:
                value = ""
                if r.Channel != None:
                    if r.Channel & 0x01 == 0x01:
                        value += "LC"
                    if r.Channel & 0x02 == 0x02:
                        value += "HC"
                    if r.Channel & 0x04 == 0x04:
                        value += "LS"
                    if r.Channel & 0x08 == 0x08:
                        value += "HS"
            elif j == 8:
                value = r.Content1
            elif j == 9:
                value = r.Content2
            elif j == 10:
                value = r.Content3
            elif j == 11:
                value = r.Content4
            elif j == 12:
                value = r.Content10
            elif j == 13:
                value = r.Content20
            elif j == 14:
                value = r.Content30
            elif j == 15:
                value = r.Content40
            elif j ==16:
                value = r.Area01
            elif j == 17:
                value = r.Area02
            elif j == 18:
                value = r.Area1
            elif j == 19:
                value = r.Area2
            elif j == 20:
                value = r.Area3
            elif j == 21:
                value = r.Area4
            elif j == 22:
                value = r.MethodName
            elif j == 23:
                value = r.UserName
            modelIndex = model.index(row, j)
            model.setData(modelIndex, value, Qt.DisplayRole)
            model.itemFromIndex(modelIndex).setTextAlignment(Qt.AlignHCenter)

    def checkLeck(self, type: int):
        if type == 0:  # 整体检漏
            self.cardOpenValve(self.systemconfig.daq.valveGeneralOxyen,
                               self.systemconfig.daq.valveFurnaceRear,
                               self.systemconfig.daq.valveBackblow,
                               self.systemconfig.daq.valveLance,
                               self.systemconfig.daq.valveFurnaceChamber,
                               )
            self.cardCloseValve(self.systemconfig.daq.valveEmit,
                                self.systemconfig.daq.valveBrushFurnace,
                                self.systemconfig.daq.valveEvacuate,
                                )
            self.cardOutput()
        if type == 1:  # 1段检漏
            self.cardOpenValve(self.systemconfig.daq.valveGeneralOxyen, )
            self.cardCloseValve(self.systemconfig.daq.valveFurnaceRear,
                                self.systemconfig.daq.valveBackblow,
                                self.systemconfig.daq.valveLance,
                                self.systemconfig.daq.valveFurnaceChamber,
                                self.systemconfig.daq.valveEmit,
                                self.systemconfig.daq.valveBrushFurnace,
                                self.systemconfig.daq.valveEvacuate, )
            self.cardOutput()
        if type == 2:
            self.cardOpenValve(self.systemconfig.daq.valveGeneralOxyen,
                               self.systemconfig.daq.valveLance,
                               self.systemconfig.daq.valveFurnaceChamber, )
            self.cardCloseValve(self.systemconfig.daq.valveFurnaceRear,
                                self.systemconfig.daq.valveBackblow,
                                self.systemconfig.daq.valveEmit,
                                self.systemconfig.daq.valveBrushFurnace,
                                self.systemconfig.daq.valveEvacuate, )
            self.cardOutput()
        if type == 3:
            self.cardOpenValve(self.systemconfig.daq.valveEmit,
                               self.systemconfig.daq.valveGeneralOxyen,
                               self.systemconfig.daq.valveFurnaceRear,
                               self.systemconfig.daq.valveBackblow, )
            self.cardCloseValve(self.systemconfig.daq.valveBrushFurnace,
                                self.systemconfig.daq.valveEvacuate,
                                self.systemconfig.daq.valveLance,
                                self.systemconfig.daq.valveFurnaceChamber, )
            self.cardOutput()

    def controlCarrier(self, open: bool):
        if open:
            self.cardOpenValve(self.systemconfig.daq.valveGeneralOxyen)
        else:
            self.cardCloseValve(self.systemconfig.daq.valveGeneralOxyen)
        self.cardOutput()

cs_598 = CS598()
